import {Component, ViewChild, ChangeDetectorRef, ElementRef} from '@angular/core';
import {
    LoadingController,
    AlertController,
    IonicPage,
    Select,
    NavController,
    NavParams,
    Platform,
    Events,
    ToastController
} from 'ionic-angular';
import {AdpMap} from "../../../components/adp-map/adp-map";
import {MapProvider} from "../../../providers/map/map-provider";
import {EventHubService} from "../../../services/event-hub.service";
import {CallNumber} from '@ionic-native/call-number';
import {GeolocateType} from "../../../components/adp-map/models/geolocate-type";
import {MapApi} from "../../../model/map/MapApi";
import {IMapBusiness} from "../../../components/adp-map/imap-business";
import {MapBusinessFactory} from "../../../components/adp-map/map-business-factory";
import {MapStrZh} from '../../../model/map/internationalized';
import {AdpMapCommon} from "../../../components/adp-map/adp-map-common";
import {PermissionsService} from "../../../services/native/permissions/permissions.service";
import {MessageBushService} from "../../../services/common/message-bush.service";
import {LaunchNavigator} from '@ionic-native/launch-navigator';
import {ClientListProvider} from "../../../providers/client/client-list/client-list.provider";

import {ClientIndividualProvider} from "../../../providers/client/client-individual/client-individual.provider";
import {ClientProspectiveProvider} from "../../../providers/client/client-prospective/client-prospective.provider";
import {ClientMapProvider} from "../../../providers/client/client-map/client-map.provider";
import {CallNumberService} from "../../../services/native/call-number/call-number.service";
import {ClientNoteEditProvider} from "../../../providers/client/client-note/client-note-edit/client-note-edit.provider";
import {LoadingService} from "../../../services/common/loading.service";
import {AdpActionSheetController} from "../../../components/common/adp-action-sheet/adp-action-sheet-controller";
import { Diagnostic } from '@ionic-native/diagnostic';

@IonicPage()
@Component({
    selector: 'page-client-bmap',
    templateUrl: 'client-bmap.html',
    providers: [
        CallNumber,
        LaunchNavigator,
        AdpMapCommon,
        PermissionsService,
        ClientIndividualProvider,
        ClientProspectiveProvider,
        ClientListProvider,
        ClientMapProvider,
        CallNumberService,
        ClientNoteEditProvider,
        LoadingService,
        Diagnostic,
        AdpActionSheetController
    ]
})

export class ClientBMapPage {
    @ViewChild('adpMap') adpMap: AdpMap;
    @ViewChild('selectMobile') selectMobile: Select;

    //地图范围列表
    public selectTypes: any = [
        {type: 1000, name: '1公里', selected: false},
        {type: 3000, name: '3公里', selected: false},
        {type: 5000, name: '5公里', selected: false},
        {type: 10000, name: '10公里', selected: false}
    ];
    //默认选择范围
    public selectedType: number = null;

    //位置提醒显示选择公里
    private infoSelectName:string = null;

    //位置提醒选择的位置
    private infoAddress:string=null;

    //位置提醒显示的总个数
    private infoTotalNum:number = 0;

    //位置重复点列表
    private clientInfoList:any = null;

    //位置重复点索引
    private clientInfoListIndex:number = 0;

    //地图点标记选中样式
    private labelStyle = null;

    //搜索时间戳id
    private inputIdTime = null;

    //用户当前定位坐标地址
    private userLocationAddress:string = null;

    currentCustomer: any;   //当前选中的客户
    currentRefCustomer: any; //当前需要重新加载的客户
    currentMobileList;  //当前客户电话列表
    currentMobile: any;      //拨打的号码
    mapCenter: any = {
        marker: null,
        point: null,
        circle: null,
        address: null,
        userLocal: null,
        AutoComplete:null,  //搜索下拉框对象
    };
    //地点搜索
    private _searchDestination: string;
    get searchDestination() {
        return this._searchDestination;
    }

    set searchDestination(val: string) {
        try {
            this.ref.detectChanges();
        } catch (e) {
        }
        this._searchDestination = val;
    }

    isSearchFlag: boolean = false;   //标记目的地搜索，如果存在，切换的时候添加目的地标记
    mapApi: MapApi;
    eventHubKey: string = 'map-page';
    showNavTools: boolean = false;
    mapBusiness: IMapBusiness;
    navCustomerParams: any;
    historyCustomerMarkers: any;
    nearCustomerMarkers: any[];  //用户附近的客户标注对象与label对象
    isMobileWeb: boolean;    //chrome模拟测试数据
    customerDefaultLocation: any = {
        lng: null,    //客户默认地址经度
        lat: null,     //客户默认地址纬度
        address: null    //客户默认地址
    };
    // 标记android媒体授权
    private androidPermission: any[] = [];
    mapOperGlobal;
    allContactData;

    LBSPageIndex = 1;    //LBS检索分页页码,默认为1，为了计算方便取第一页
    LBSPageSize = 50;   //LBS检索分页条数，最多50
    LBSTotal = null;    //LBS检索总数
    LBSCacheList: any[] = [];    //缓存检索结果集

    constructor(public navCtrl: NavController,
                public navParams: NavParams,
                public mapProvider: MapProvider,
                public alertCtrl: AlertController,
                private callNumber: CallNumber,
                public ref: ChangeDetectorRef,
                public el: ElementRef,
                public loadingCtrl: LoadingController,
                public toast: ToastController,
                public platform: Platform,
                private permissionsService: PermissionsService,
                private launchNavigator: LaunchNavigator,
                public adpMapCommon: AdpMapCommon,
                public clientProvider: ClientListProvider,
                private callNumberService: CallNumberService,
                public clientMapProvider: ClientMapProvider,
                public loadingService:LoadingService,
                private diagnostic: Diagnostic,
                private adpActionSheetController:AdpActionSheetController,
                private events:Events
    ) {

        this.selectedType = 3000;
        this.changeSelectedType();
        this.mapBusiness = MapBusinessFactory.getMapBusiness();
        this.nearCustomerMarkers = [];
        this.isMobileWeb = this.platform.is('mobileweb');
        this.inputIdTime = new Date().getTime();
        // this.getAllClient();
    }

    ionViewDidLoad() {
        this.events.publish('checkNet');
        if (this.isMobileWeb) {
            this.startLocation();
            return;
        }
        let msg = '';
        this.permissionsService.locationAuthorized().then(r=>{
            if(this.platform.is('android')){
                msg = '请到"设置"中启用定位模式为“使用GPS、WLAN、蓝牙或移动网络确定位置”，允许访问位置信息';
            }
            if(this.platform.is('ios')){
                msg = '请到"设置>隐私>定位服务"选项中，启用定位服务，允许访问位置信息';
            }
            if(r[0] && r[1]){
                this.startLocation();
            }else{
                this.alertCtrl.create({
                    message:msg,
                    cssClass: 'bmap-alert',
                    buttons:[
                        {
                            text: '确定'
                        }
                    ]
                }).present();
            }
        }).catch(e=>{
            console.log(e);
            this.alertCtrl.create({
                message: msg,
                cssClass: 'bmap-alert',
                buttons:[
                    {
                        text: '确定'
                    }
                ]
            }).present();
        });
    }

    /**
     * 执行定位
     */
    startLocation() {
        this.mapBusiness = MapBusinessFactory.getMapBusiness();
        let self = this;

        //region 接受客户路由信息
        let initPoi = {
            lat: 31.234576,
            lng: 121.475638,
            geolocatedType: GeolocateType.UserLocation
        };

        this.navCustomerParams = {
            id: this.navParams.get('id') || '',
            address:this.navParams.get('address'),
            latitude:this.navParams.get('latitude') || '',
            longitude:this.navParams.get('longitude') || '',
            type: this.navParams.get('type') || '',
            clientRole:this.navParams.get('clientRole') || ''       //I-投保人，O-被保人，IO-投被保
        };

        if (this.navCustomerParams && this.navCustomerParams.address) {
            initPoi.geolocatedType = GeolocateType.CustomerLocation;
            //被保人不显示在地图上，显示目的地图标
            if(this.navCustomerParams.clientRole == 'O'){
                this.isSearchFlag = true;
            }
            if(this.navCustomerParams.latitude&&this.navCustomerParams.longitude){
                this.infoAddress = this.navCustomerParams.address;
                initPoi.lng = this.navCustomerParams.longitude;
                initPoi.lat = this.navCustomerParams.latitude;
            }else{
                // this.showToastMessage('地址解析错误');
                // return;
                this.clientMapProvider.cloudgc(this.navCustomerParams.address).subscribe(r=>{
                    if(!self.isMobileWeb){
                        r = JSON.parse(r);
                    }
                    if(r&&r.status == 0){
                        if(r.result&&r.result.length){
                            this.infoAddress = this.navCustomerParams.address;
                            this.navCustomerParams.location = r.result[0].location;
                            initPoi.lng = this.navCustomerParams.location.lng;
                            initPoi.lat = this.navCustomerParams.location.lat;
                            this.adpMap.create(
                                initPoi.lat,
                                initPoi.lng,
                                "mapPageMapContainer",
                                initPoi.geolocatedType
                            );
                        }else {
                            this.showToastMessage('地址解析错误');
                        }
                    }else {
                        this.showToastMessage('地址解析错误');
                    }
                });
            }
        }

        this.mapOperGlobal = window['map-global-utility'] = window['map-global-utility'] || {};

        //地图初始化完成
        EventHubService.on("map-ready", this.eventHubKey, (options) => {
            self.mapReadyHandle(options);
        });
        //地图开始定位
        EventHubService.on("map-geolocate-start", this.eventHubKey, (options) => {
            if (options.origin === this.eventHubKey) {
                this.mapOperGlobal.loadingCover = this.loadingCtrl.create({spinner: 'circles',content: "正在定位 . . ."});
                this.mapOperGlobal.loadingCover.present();
            }
        });
        //定位完成
        EventHubService.on("map-geolocated", this.eventHubKey, (options) => {
            if (this.mapOperGlobal.loadingCover)
                this.mapOperGlobal.loadingCover.dismissAll();
            self.getUserLocal(1, options);
            self.mapGeolocated(options);
        });
        //定位失败
        EventHubService.on("map-geolocate-failured", this.eventHubKey, () => {
            if (this.mapOperGlobal.loadingCover) {
                try {
                    this.mapOperGlobal.loadingCover.dismiss();
                } catch (e) {
                }
            }
            let msg = MapStrZh.GeolocateFailure;
            this.showToastMessage(msg);
        });
        //返回用户初始位置
        EventHubService.on("map-go-user-location", this.eventHubKey, (options) => {
            // self.mapGeolocated(options);
            self.getUserLocal(2, options);
        });

        this.adpMap.create(
            initPoi.lat,
            initPoi.lng,
            "mapPageMapContainer",
            initPoi.geolocatedType
        );
    }

    ionViewDidEnter() {
        let flag = MessageBushService.getMessage(MessageBushService.keys.clientMapCustomerDetailUpdated);
        if (flag == "1") {
            //重新获取当前客户
            MessageBushService.setMessage(MessageBushService.keys.clientMapCustomerDetailUpdated, "0");
            if (this.currentRefCustomer && this.currentRefCustomer.clientCode) {
                let clientCode = this.currentRefCustomer.clientCode;
                let userType = this.currentRefCustomer.userType;
                this.getCurrentCustomerDetail(true, clientCode, userType,location);
            }
        }
    }

    filterClientData(clientList) {
        return clientList.map(c => {
            return {
                clientId: c.clientId,
                leadsId: c.leadsId,
                gender: c.gender,
                name: c.name
            }
        });
    }

    getAllClient() {
        const contactDataJson = localStorage.getItem('mapClientList');
        if (contactDataJson) {
            this.allContactData = JSON.parse(contactDataJson);
        } else {
            this.clientProvider.getClientsFromServer().subscribe(result => {
                let clientData = this.filterClientData(result.clientList.concat(result.leadList));
                localStorage.setItem('mapClientList', JSON.stringify(clientData));
                this.allContactData = clientData;
            });
        }
    }

    /**
     * 统一消息提示
     * @param {string} msg
     */
    showToastMessage(msg:string){
        this.toast.create({
            message: msg,
            duration: 3000,
            position: 'middle',
        }).present();
    }

    /**
     * 跳转到客户详情
     */
    goCustomerDetail() {
        let role = this.currentCustomer.clientRole;
        let id = this.currentCustomer.clientId;
        let leadId = this.currentCustomer.leadId;
        const clientRole = role;
        //准客户详情
        if (leadId) {
            this.navCtrl.push('ClientDetailPage', {
                clientNum: leadId,
                leads: true
            });
        } else {
            /*if (role == 'O') {
                this.navCtrl.push('HolderClientDetailPage', {
                    clientNum: id,
                    role: clientRole
                })
            } else if (role == 'IO') {
                this.navCtrl.push('HolderClientDetailPage', {
                    clientNum: id,
                    role: clientRole
                })
            } else {
                this.navCtrl.push('InsuredClientDetailPage', {
                    clientNum: id,
                    role: clientRole
                })
            }*/
            this.navCtrl.push('HolderClientDetailPage', {
                clientNum: id,
                role: clientRole
            })
        }
    }

    /**
     * 获取当前用户位置
     * @param typeState
     * @param data
     */
    getUserLocal(typeState, data) {
        //设置用户定位标注
        let userLocalIconPath = './assets/images/map/icon_location.png';

        //删除用户定位标记
        if (this.mapCenter.userLocal) {
            this.mapBusiness.removeOverlay(data.mapApi, this.mapCenter.userLocal);
        }

        //删除目的地标记
        if (this.mapCenter.marker) {
            this.mapBusiness.removeOverlay(data.mapApi, this.mapCenter.marker);
        }

        //其他页面跳转过来不主动执行定位
        if (data.geolocatedType === GeolocateType.CustomerLocation) {
            return;
        }
        //使用初始化获取的坐标值,标记位置
        if (typeState === 1) {
            this.mapCenter.userLocal = this.mapBusiness.addMarkerByPoint(
                data.center,
                data.mapApi,
                userLocalIconPath,
                false,
                -1
            );
            //获取坐标所在名称
            this.setInputValue(data);
        } else if (typeState === 2) {
            //用户主动调用定位，使用GPS坐标值
            let self = this;
            self.isSearchFlag = false;
            //调用原生GPS定位
            this.mapOperGlobal = window['map-global-utility'];

            this.mapOperGlobal.loadingCover = this.loadingCtrl.create({spinner: 'circles',content: "定位中. . ."});
            this.mapOperGlobal.loadingCover.present();

            this.adpMapCommon.nativeGeolocate(this.mapApi, (res) => {
                if (this.mapOperGlobal.loadingCover) {
                    this.mapOperGlobal.loadingCover.dismissAll();
                }
                if (self.isMobileWeb) {
                    //todo 模拟定位效果
                    res.lat = 30.543067;
                    res.lng = 104.077109;
                }
                console.log(res);
                if (res.lng && res.lat) {
                    //清除已经搜索的关键词
                    self.cleanSearchKey();
                    self.mapCenter.userLocal = self.mapBusiness.addMarkerByPoint(
                        res,
                        self.mapApi,
                        userLocalIconPath,
                        false,
                        -1
                    );
                    self.mapBusiness.panTo(res, self.mapApi);
                    data.center = res;
                    data.geolocatedType = GeolocateType.UserLocation;
                    self.mapGeolocated(data);
                    //获取坐标所在名称
                    self.setInputValue(data);
                } else {
                    let msg = MapStrZh.GeolocateFailure;
                    this.showToastMessage(msg);
                }
            });
        }
    }

    /**
     * 定位之后信息提醒为当前位置名称
     */
    setInputValue(data){
        this.mapBusiness.getAddressByPoint(data.mapApi,data.center,(res)=>{
            this.infoAddress = res;
            this.userLocationAddress = res;
            this.ref.detectChanges();
        });
    }

    /**
     * 获取当前用户所在位置地址
     */
    getUserLocalAddress(ev){
        //调用原生GPS定位
        this.mapOperGlobal = window['map-global-utility'];
        this.mapOperGlobal.loadingCover = this.loadingCtrl.create({spinner: 'circles',content: "定位中. . ."});
        this.mapOperGlobal.loadingCover.present();
        this.adpMapCommon.nativeGeolocate(this.mapApi, (res) => {
            if (this.mapOperGlobal.loadingCover) {
                this.mapOperGlobal.loadingCover.dismissAll();
            }
            if (this.isMobileWeb) {
                //todo 模拟定位效果
                res.lat = 30.543067;
                res.lng = 104.077109;
            }
            if (res.lng && res.lat) {
                let point = res;
                this.mapBusiness.getAddressByPoint(this.mapApi,point,(addr)=>{
                    this.userLocationAddress = addr;
                    this.ref.detectChanges();
                    this.navOnAppHandle(ev);
                });
            } else {
                let msg = MapStrZh.GeolocateFailure;
                this.showToastMessage(msg);
            }
        });
    }

    /**
     * 地图中心位置确认
     * @param data
     */
    mapGeolocated(data) {
        let point = this.mapCenter.point = data.center;
        this.destinationed(point, this.mapApi);
        if (data.geolocatedType === GeolocateType.CustomerLocation) {
            if(this.navCustomerParams.clientRole == 'O'){
                this.mapCenter.marker = this.mapBusiness.addMarkerByPoint(
                    point,
                    data.mapApi,
                    '',
                    false,
                    -1
                );
            }
        }
    }

    //目的地确定后范围搜索客户
    destinationed(point, mapApi1: MapApi) {
        if (!mapApi1 || !mapApi1._mapInstance) return;
        let self = this;
        self.removePrevCustomer(true, mapApi1);
        //设置圆形（使用多边形）
        this.mapCenter.circle = self.mapBusiness.addCircle(point, this.selectedType, mapApi1);

        //从微服务获取附近客户(可用)
        this.getNearCustomerByMS(point,mapApi1);

        let zoomIndex: number = 13;  //默认地图缩放
        switch (this.selectedType) {
            case 1000:
                zoomIndex = 15;
                break;
            case 3000:
                zoomIndex = 13;
                break;
            case 10000:
                zoomIndex = 12;
                break;
            default:
                zoomIndex = 13;
        }
        this.mapBusiness.setZoom(zoomIndex, this.mapApi);
        this.mapBusiness.panTo(point,mapApi1);
    }

    /**
     * 从微服务获取附近客户(可用)
     * @param point
     * @param mapApi1
     */
    getNearCustomerByMS(point, mapApi1) {
        this.mapProvider.getNearCustomers(point, this.selectedType).subscribe(res => {
            this.infoTotalNum = res.amount;
            if (Array.isArray(res.data)) {
                this.drawCustomerMaker(res.data, mapApi1);
            }
        });
    }

    /**
     * @function 在地图上绘制客户maker
     * @param contacts
     * @param mapApi1
     */
    drawCustomerMaker(contacts, mapApi1) {
        let points = [];
        let self = this;
        contacts.forEach(customer => {
            //标记客户头像，多个用户图标不一样
            let iconPath:string = null;
            let name:string = null;
            let isMore:boolean = false;
            if(customer.clientInfo.length >=2){
                //多人图标
                iconPath = './assets/images/map/icon_people_map.png';
                //标记多个名字显示
                isMore = true;
            }else{
                //添加客户位置标注
                iconPath = MapProvider.getCustomerAvatar(customer.clientInfo[0]);
                isMore = false;
            }
            name = customer.clientInfo[0].name;
            customer.avatar = iconPath;
            let point = {lng: customer.lng, lat: customer.lat};
            points.push(point);
            let customerMarker = self.mapBusiness.addMarkerByPoint(
                point,
                mapApi1,
                iconPath,
                false,
                2
            );
            if (!customerMarker) return;
            //添加客户label
            let label = self.mapBusiness.addLabelForMarker(
                mapApi1,
                customerMarker,
                point,
                33,
                5,
                name,
                isMore
            );
            customerMarker.customer = label.customer = customer;
            this.nearCustomerMarkers.push({
                marker: customerMarker,
                label
            });

            //添加客户标注点击事件监听
            customerMarker.addEventListener("click", e => {
                self.markerClickHandle(e,label);
            });
            label.addEventListener("click", e => {
                self.markerClickHandle(e,label);
            });

        });
        this.ref.detectChanges();
    }

    /**
     * 标注单击
     * @param event
     * @param label
     * userType=1 准客户
     * userType=2 核心客户
     */
    markerClickHandle(event,label) {
        this.labelStyle = label;
        if (event.currentTarget) {
            this.clientInfoList = event.currentTarget.customer;
            this.clientInfoListIndex = 0;
            this.checkCustomerDetail();
        }
    }

    /**
     * 获取当前点击客户
     */
    checkCustomerDetail(){
        let location = [this.clientInfoList.lng,this.clientInfoList.lat];
        let clientCode = this.clientInfoList.clientInfo[this.clientInfoListIndex].clientCode;
        let userType = this.clientInfoList.clientInfo[this.clientInfoListIndex].userType;
        this.currentRefCustomer = {
            clientCode:clientCode,
            userType:userType
        };
        this.getCurrentCustomerDetail(false, clientCode, userType,location);
    }

    /**
     * 上一个
     */
    preClient(){
        if (this.clientInfoListIndex ===0) return;
        this.clientInfoListIndex --;
        this.checkCustomerDetail();
    }

    /**
     * 下一个
     */
    nextClient(){
        if (this.clientInfoListIndex ===this.clientInfoList.clientInfo.length-1) return;
        this.clientInfoListIndex ++;
        this.checkCustomerDetail();
    }

    /**
     * 获取当前客户详情
     * @param {boolean} state  true状态表示获取客户详情之后需要重新获取当前客户范围客户
     * @param {string} clientCode
     * @param {number} userType
     * @param {any} location
     */
    getCurrentCustomerDetail(state?: boolean, clientCode?: string, userType?: number,location?:any) {
        this.loadingService.showLoading();
        this.mapProvider.getCustomerDetail(clientCode, userType).subscribe(detail => {
            this.loadingService.dismissLoading();
            this.currentCustomer = null;
            this.currentCustomer = detail;
            this.labelStyle.setStyle({border:'2px solid #35ac63'});
            this.customerDefaultLocation.lng = location[0];
            this.customerDefaultLocation.lat = location[1];
            //获取客户头像
            this.currentCustomer.avatar = MapProvider.getCustomerAvatarDetail(this.currentCustomer);
            //获取客户电话列表
            this.currentCustomer.mobilePhone = this.currentCustomer.mobilePhone || this.currentCustomer.mobileList;
            //获取线索列表
            // this.currentCustomer.tagList = ["\u4eba\u5de5\u7ebf\u7d22","\u4eba\u5de5\u7ebf\u7d22","\u4eba\u5de5\u7ebf\u7d22"];
            if (this.currentCustomer.tagList && this.currentCustomer.tagList.length) {
                let list = [];
                this.currentCustomer.tagList.map((e) => {
                    list.push(window['unescape'](e.replace(/\\u/g, '%u')));
                });
                this.currentCustomer.tagList = list;
            }else {
                this.currentCustomer.tagList = [];
            }
            if (this.currentCustomer.addressList && this.currentCustomer.addressList.length) {
                this.currentCustomer.addressList.map((e) => {
                    if (e.defaultIndicator === 1) {
                        this.currentCustomer.address = e.address;
                    }
                });
            }

            //坐标更新需要重新搜索当前范围客户
            if (state) {
                this.getCustomerDefaultLocation();
                //以客户为中心点搜索
                let point = {
                    lng: this.customerDefaultLocation.lng,
                    lat: this.customerDefaultLocation.lat
                };
                //以搜索目的地为中心点搜索
                this.destinationed(this.mapCenter.point, this.mapApi);
            }
            this.ref.detectChanges();
        },err=>{
            this.loadingService.dismissLoading();
        });
    }

    //删除上次检索的客户标注与label
    removePrevCustomer(isCleanAll?: boolean, mapApi: MapApi = null) {
        //清除可能存在的导航路线
        if (isCleanAll) {
            mapApi._mapInstance.clearOverlays();
        }
        if (this.mapCenter) {
            this.mapBusiness.removeOverlay(mapApi, this.mapCenter.marker);
            this.mapBusiness.removeOverlay(mapApi, this.mapCenter.circle);
        }
        this.historyCustomerMarkers = {
            mapCenter: {
                marker: this.mapCenter.marker,
                circle: this.mapCenter.circle
            },
            customerMarkers: []
        };

        if (this.nearCustomerMarkers && Array.isArray(this.nearCustomerMarkers)) {
            this.nearCustomerMarkers.forEach(customer => {
                this.mapBusiness.removeOverlay(mapApi, customer.marker);
                this.mapBusiness.removeOverlay(mapApi, customer.label);
                this.historyCustomerMarkers.customerMarkers.push(customer);
            });
        }
        this.nearCustomerMarkers = [];
        this.infoTotalNum = 0;
        this.ref.detectChanges();
    }

    /**
     * 地图加载完成
     * @param data
     */
    mapReadyHandle(data) {
        this.mapApi = data.mapApi;
        this.mapBusiness.addZoomControl(this.mapApi);
        this.destinationAc();
    }

    //用户点击建议项目，目的地搜索
    destinationAc() {
        let desInput = document.querySelector('#destinationInput'+this.inputIdTime+' input') as HTMLInputElement;
        this.mapCenter.AutoComplete = this.mapBusiness.autoCompeleted(this.mapApi, desInput, (res) => {
            this.closeCustomer();
            this.searchDestination = res;
            this.infoAddress = res;
            setTimeout(() => {
                desInput.blur();
            }, 20);
            this.ref.detectChanges();
            this.mapCenter.AutoComplete.setInputValue(res);
            this.isSearchFlag = true;
            this.mapBusiness.searchDestination(this.searchDestination, this.mapApi, res => {
                this.searchDestResult(res);
            });
        });
    }

    //目的地搜索返回结果
    searchDestResult(result) {
        this.destinationed(result.point, this.mapApi);
        this.mapCenter.point = result.point;
        this.mapCenter.marker = this.mapBusiness.addMarkerByPoint(
            result.point,
            this.mapApi,
            '',
            false,
            -1
        );
        this.mapBusiness.panTo(result.point, this.mapApi);
    }

    /**
     * 获取选择地址范围
     * @param type
     */
    getSelectedType(type) {
        this.selectedType = type;
        this.LBSPageIndex = 1;
        console.log(this.selectedType);
        this.changeSelectedType();
        this.destinationed(this.mapCenter.point, this.mapApi);
        if (this.isSearchFlag) {
            this.mapCenter.marker = this.mapBusiness.addMarkerByPoint(
                this.mapCenter.point,
                this.mapApi,
                '',
                false,
                -1
            );
        }
    }

    /**
     * 改变选中标识
     */
    changeSelectedType() {
        this.selectTypes.map((item) => {
            item.selected = false;
            if (item.type === this.selectedType) {
                item.selected = true;
                this.infoSelectName = item.name;
            }
        });

        this.closeCustomer();
    }

    /**
     * 清除搜索词
     */
    cleanSearchKey() {
        this.searchDestination = '';    //清除搜索的目的地
        this.mapCenter.AutoComplete.setInputValue('');
    }

    /**
     *  返回
     */
    backButtonClick() {
        this.navCtrl.pop(null);
    }

    /**
     * 关闭弹层
     */
    closeCustomer() {
        this.currentCustomer = null;
        let tm:any = setTimeout(()=>{
            this.currentCustomer = null;
            window.clearTimeout(tm);
        },20);
        if(this.labelStyle){
            this.labelStyle.setStyle({border:'1px solid #999'});
            this.labelStyle = null;
        }
        try {
            this.ref.detectChanges();
        } catch (e) {
        }
    }

    /**
     * vip 等级描述映射
     * @param level
     * @returns {string}
     */
    getDescribeByVipLevel(level) {
        let result = '';
        if (level == 1) {
            result = '黄金会员';
        } else if (level == 2) {
            result = '白金会员';
        } else if (level == 3) {
            result = '宏运世家钻石';
        } else if (level == 4) {
            result = '宏运世家至尊';
        }
        return result;
    }

    /**
     * 拨打电话
     * @param ev
     */
    callCustomerHandle(ev) {
        ev.preventDefault();
        ev.stopPropagation();

        this.currentMobileList = this.currentCustomer.mobilePhone;
        if (!this.currentMobileList || this.currentMobileList.length < 1) return;
        if (this.currentMobileList.length === 1 && this.currentMobileList[0].mobile) {
            this.currentMobile = this.currentMobileList[0].mobile;
            this.nativeCallPhone();
            return;
        }
        if(this.currentMobileList.length > 1){
            const phoneArray = [];
            this.currentMobileList.forEach(phoneNumItem => {
                phoneArray.push({
                    text:phoneNumItem.mobile,
                    handler:() => {
                        this.nativeCallPhone(phoneNumItem.mobile)
                    }
                });
            });
            this.adpActionSheetController.create({
                title:"选择电话",
                buttons:phoneArray
            }).present();

        }

        // setTimeout(() => {
        //     this.selectMobile.open();
        // }, 20);
        // this.ref.detectChanges();
    }

    /**
     * 调用原生拨打电话
     * @param {string} mobilePhone
     */
    nativeCallPhone(mobilePhone?: string) {
        if (mobilePhone) {
            this.currentMobile = mobilePhone;
        }
        // let __this = this;
        // if (this.currentMobile) {
        //     __this.callNumber.callNumber(this.currentMobile, true)
        //         .then(() => console.log('对话框启动成功!'))
        //         .catch(() => console.log('对话框启动失败!'));
        // }

        console.log(this.currentMobile);

        this.callNumberService.makeCall(this.currentMobile,
            this.callNumberService.initClientNoteLog(this.currentCustomer.clientId),
            true ,
            this.callNumberService.initFollowStateLog(this.currentCustomer.clientId));
    }

    /**
     * 获取当前客户的默认地址
     */
    getCustomerDefaultLocation() {
        this.customerDefaultLocation.address = null;
        if (this.currentCustomer && this.currentCustomer.addressList) {
            let addressList = this.currentCustomer.addressList;
            if (addressList && addressList.length) {
                addressList.map((item) => {
                    if (item.defaultIndicator === 1) {
                        this.customerDefaultLocation.address = item.address;
                    }
                });
            }
        }
    }

    /**
     * 路线
     * @param ev
     */
    navCustomerHandle(ev) {
        ev.preventDefault();
        ev.stopPropagation();

        this.getCustomerDefaultLocation();
        if (!this.customerDefaultLocation.lng && !this.customerDefaultLocation.lat) {
            this.showToastMessage('客户地址无效，无法规划路线');
            return;
        }

        this.mapOperGlobal = window['map-global-utility'];

        this.mapOperGlobal.loadingCover = this.loadingCtrl.create({content: "加载中. . ."});
        this.mapOperGlobal.loadingCover.present();

        let self = this;
        //定位用户当前位置
        this.adpMapCommon.nativeGeolocate(this.mapApi, (res) => {
            if (this.mapOperGlobal.loadingCover)
                this.mapOperGlobal.loadingCover.dismissAll();
            if (self.isMobileWeb) {
                //todo 模拟定位效果
                res.lat = 30.663049;
                res.lng = 104.086308;
            }
            if (res.lat && res.lng) {
                let startPoint = res;
                let endPoint = {
                    lng: self.customerDefaultLocation.lng,
                    lat: self.customerDefaultLocation.lat
                };
                //取消移除当前所有标记
                self.removePrevCustomer(true, self.mapApi);

                self.getSelectedType(self.selectedType);
                //1.拿到当前客户location和自身定位location
                //2.查询驾车路线
                //3.关闭当前用户弹窗
                self.mapBusiness.generateDriveRoute(startPoint, endPoint, self.mapApi);

                self.closeCustomer();
                self.showNavTools = true;

                try {
                    self.ref.detectChanges();
                } catch (e) {
                }

            } else {
                let msg = MapStrZh.GeolocateFailure;
                this.showToastMessage(msg);
            }
        });
    }

    /**
     * 原生导航
     * @param ev
     */
    navOnAppHandle(ev) {
        ev.preventDefault();
        ev.stopPropagation();

        this.getCustomerDefaultLocation();
        // if (!this.customerDefaultLocation.lng && !this.customerDefaultLocation.lat) {
        //     this.showToastMessage('客户地址无效，无法导航');
        //     return;
        // }
        let destination = this.customerDefaultLocation.address;
        let options = {
            start: '',
            app: 'baidu'
        };
        if(this.userLocationAddress){
            options.start = this.userLocationAddress;
            this.launchNavigator.isAppAvailable('baidu').then(appIsAvailable => {
                if (appIsAvailable) {
                    this.launchNavigator.navigate(destination, options).then(
                        success => console.log('launched nav'),
                        error => {
                            this.showToastMessage('百度地图打开失败!');
                        });
                } else {
                    this.showToastMessage('请安装百度地图app!');
                }
            });
        }else{
            this.getUserLocalAddress(ev);
        }
    }
}
